package cn.ronghuanet.auth.interceptors;

import cn.ronghuanet.base.util.AjaxResult;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 登录拦截
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录拦截,如果没有登录就要返回错误信息
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1 获取请求头中的token
        String token = request.getHeader("token");

        // 2 如果token为空,说明未登录,要返回错误信息并拦截
        if(StringUtils.isBlank(token)){
            AjaxResult ajaxResult = AjaxResult.error("noLogin");
            response.getWriter().print(JSONObject.toJSONString(ajaxResult));
            return false;
        }

        // 3 根据token作为key,去redis中获取登录信息
        Object obj = redisTemplate.opsForValue().get(token);

        // 4 如果登录信息为空,说明未登录,要返回错误信息并拦截
        if(Objects.isNull(obj)){
            AjaxResult ajaxResult = AjaxResult.error("noLogin");
            response.getWriter().print(JSONObject.toJSONString(ajaxResult));
            return false;
        }

        // 如果不为空,说明已经登录过就放行,并且重新给该key所在的redis设置30分钟过期时间
        redisTemplate.opsForValue().set(token,obj,30, TimeUnit.MINUTES);
        return true;
    }
}
